﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Globalization;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.IO;

namespace Elentok.Common.Wpf.ValueConverters
{
  /// <summary>
  /// Converts from <see cref="byte"/>[] or <see cref="IArrayWrapper&lt;T&gt;"/>
  /// to <see cref="ImageSource"/>.
  /// </summary>
  public class BytesToImageSourceConverter : IValueConverter
  {
    /// <summary>
    /// Converts from <see cref="byte"/>[] or <see cref="IArrayWrapper&lt;T&gt;"/>
    /// to <see cref="ImageSource"/>.
    /// </summary>
    /// <param name="value"></param>
    /// <param name="targetType"></param>
    /// <param name="parameter"></param>
    /// <param name="culture"></param>
    /// <returns></returns>
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
      #region Get bytes from value
      byte[] bytes = value as byte[];
      if (bytes == null && value is IArrayWrapper<byte>)
        bytes = ((IArrayWrapper<byte>)value).ToArray();

      if (bytes == null)
        return null;
      #endregion

      BitmapImage bitmap = new BitmapImage();
      bitmap.BeginInit();
      bitmap.StreamSource = new MemoryStream(bytes);
      bitmap.EndInit();
      return bitmap;
    }

    /// <summary>
    /// NOT IMPLEMENTED
    /// </summary>
    /// <param name="value"></param>
    /// <param name="targetType"></param>
    /// <param name="parameter"></param>
    /// <param name="culture"></param>
    /// <returns></returns>
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      throw new NotImplementedException();
    }
  }
}
